package network;

import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-04-03
 * Time: 0:59
 */
public class UDPEchoServer {

    //定义socket对象
    private DatagramSocket socket = null;

    public UDPEchoServer(int port) throws SocketException {//main方法要处理！
        this.socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器成功");
        //服务器一直工作 或者 等待客户端请求
        while(true) {
            //读取请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024], 1024);
            //自带饭盒

            socket.receive(requestPacket);//io操作都可能会有异常
            //盛饭，从网卡里面拿的请求，将其录入已存在的数据报里

            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            //数据报解析成字符串

            String response = process(request);
            //计算该字符串的响应

            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),
                    response.getBytes().length,
                    requestPacket.getSocketAddress()); // 数据报里的客户端主机IP
            //传给客户端得转化为数据报才行
            //而计算数据报的信息计算只能以字符串为对象

            socket.send(responsePacket);
            //发送数学报，数据报有客户端的信息，所以可以具体的转发到对方机器
            //响应

            System.out.printf("客户端[%s, %d], 发来请求[request]:%s, 其将收到响应[response]:%s\n",
                    requestPacket.getAddress(), requestPacket.getPort(),
                    request, response);
            //打印日志
        }
    }

    public String process(String request) {
        //回显服务器直接返回原值~
        return request;
    }

    public static void main(String[] args) throws IOException {
        UDPEchoServer udpEchoServer = new UDPEchoServer(9090);
        udpEchoServer.start();
    }
}
